import random
import time
import uiautomation as auto
from .base_operations import WeChatBaseOperations, random_wait
import traceback

class WeChatV3Operations(WeChatBaseOperations):
    
    def __init__(self, log_fun, phone_number, name, apply_msg, prefix, tag):
        super().__init__(log_fun, phone_number, name, apply_msg, prefix, tag)
        self.wechat_window_class_name = "WeChatMainWndForPC"
        self.sidebar_btns = ["聊天", "收藏", "手机", "设置及其他"]

    def click_sidebar_entry(self):
        return self._switch_to_contacts()
    
    def add_friend(self):
        """V3加好友完整流程"""
        self._log("添加朋友")
        try:
            # 点击添加朋友按钮
            add_btn = auto.ButtonControl(Name="添加朋友")
            if not add_btn.Exists():
                return False
            self._human_click(add_btn)

            # 输入手机号
            input_box = auto.EditControl(Name="微信号/手机号")
            if not input_box.Exists():
                return False
            self._human_click(input_box)
            self._human_type(input_box, self.phone_number)
            input_box.SendKeys("{Enter}")

            # 检查搜索结果
            if not self._check_search_result(self.phone_number):
                return False

            # 执行添加操作
            return self._perform_add_action(self.name)
        except Exception as e:
            self._log(f"添加好友出错: {str(e)}")
            self._log(traceback.format_exc())
                # 获取异常堆栈信息

    def _check_search_result(self, phone_number):
        """检查搜索结果"""
        result_text = auto.TextControl(Name=f"搜索：{phone_number}")
        if not result_text.Exists():
            self._click_wechat_blank()
            return False
        self._human_click(result_text)
        return True

    def _perform_add_action(self, name):
        """执行添加操作"""
        # 检查是否已添加
        if self._check_already_added():
            self._log("已添加过该用户")
            return "已添加好友"

        # 检查用户是否存在
        if self._check_user_not_exist():
            self._log("账号不存在")
            return "账号不存在"

        # 添加到通讯录
        add_btn = auto.ButtonControl(Name="添加到通讯录")
        if not add_btn.Exists():
            return False
        self._human_click(add_btn)

        # 发送好友请求
        return self._send_friend_request(name)

    def _check_already_added(self):
        """检查是否已添加"""
        self._log("_check_already_added")
        remark = self._recursive_find_control(
            auto.GetForegroundControl(), 
            auto.TextControl, 
            "备注"
        )
        if remark:
            # 发送ESC按键退出已加用户框，因为有可能挡住取消按钮
            self._log("发送ESC按键退出已加用户框")
            auto.SendKeys("{ESC}")
            self._click_cancel_button()
            return True
        return False

    def _check_user_not_exist(self):
        """检查用户是否存在"""
        self._log("_check_user_not_exist")
        not_found = self._recursive_find_control(
            auto.GetForegroundControl(),
            auto.ListItemControl,
            "无法找到该用户，请检查你填写的账号是否正确。"
        )
        if not_found:
            self._click_cancel_button()
            return True
        return False

    def _send_friend_request(self, name):
        """发送好友请求"""
        window = auto.WindowControl(Name="添加朋友请求")
        if not window.Exists():
            return False
        
        inputs = self._find_all_edit_controls(window)
        if len(inputs) < 3:
            return False

        # 填写申请信息
        self._human_click(inputs[0])
        inputs[0].SendKeys('{Ctrl}{A}{Delete}')
        self._human_type(inputs[0], self.apply_msg.format(name=self.name))

        # 填写备注
        self._human_click(inputs[1])
        inputs[1].SendKeys('{Ctrl}{A}{Delete}')
        self._human_type(inputs[1], self.prefix + self.name)

        # 填写标签
        if self.tag != "":
            tag_arr = self.tag.split(",")
            for tag in tag_arr:
                self._human_click(inputs[2])
                self._human_type(inputs[2], tag)
                inputs[2].SendKeys('{ENTER}')

        # 点击确定
        confirm = auto.ButtonControl(searchFromControl=window, Name="确定")
        if not confirm.Exists():
            return False
        self._human_click(confirm)
        time.sleep(2)
        self._click_cancel_button()
        return "已发送好友申请"

    def _click_cancel_button(self):
        """点击取消按钮"""
        cancel = auto.ButtonControl(Name="取消")
        if cancel.Exists():
            self._log("找到了取消按钮")
            self._human_click(cancel)